<template>
    <div>
        <el-card class="!border-none mb-4" shadow="never">
            <el-form class="mb-[-16px]" :model="queryParams" inline>
                <el-form-item label="旅行社" class="w-[280px]" prop="travel_agency_id">
                    <el-select
                        v-model="queryParams.travel_agency_id"
                        clearable
                        placeholder="请选择旅行社"
                    >
                        <el-option label="全部" value=""></el-option>
                        <el-option
                            v-for="(item, index) in optionsData.trave_agency"
                            :key="index"
                            :label="item.name"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="线路名称" class="w-[280px]" prop="title">
                    <el-input v-model="queryParams.title" clearable placeholder="请输入线路名称" />
                </el-form-item>
                <el-form-item label="是否热门线路" class="w-[200px]" prop="is_hot">
                    <el-select
                        v-model="queryParams.is_hot"
                        clearable
                        placeholder="请选择是否热门线路"
                    >
                        <el-option label="全部" value=""></el-option>
                        <el-option
                            v-for="(item, index) in dictData.is_hot"
                            :key="index"
                            :label="item.name"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" class="w-[150px]" prop="status">
                    <el-select v-model="queryParams.status" clearable placeholder="请选择状态">
                        <el-option label="全部" value=""></el-option>
                        <el-option
                            v-for="(item, index) in dictData.approval_status"
                            :key="index"
                            :label="item.name"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="resetPage">查询</el-button>
                    <el-button @click="resetParams">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card class="!border-none" v-loading="pager.loading" shadow="never">
            <el-button v-perms="['travel.line/add']" type="primary" @click="handleAdd">
                <template #icon>
                    <icon name="el-icon-Plus" />
                </template>
                新增
            </el-button>
            <el-button
                v-perms="['travel.line/delete']"
                :disabled="!selectData.length"
                @click="handleDelete(selectData)"
            >
                删除
            </el-button>
            <el-button @click="downloadTemplate">下载模板</el-button>
            <el-button
                v-perms="['travel.line/import']"
                type="success"
                @click="handleImport(queryParams.travel_agency_id)"
            >
                <template #icon>
                    <icon name="el-icon-Upload" />
                </template>
                批量导入
            </el-button>
            <div class="mt-4">
                <el-table :data="pager.lists" @selection-change="handleSelectionChange">
                    <el-table-column type="selection" width="55" />
                    <el-table-column label="旅行社" prop="travel_agency_name"></el-table-column>
                    <el-table-column label="用户" prop="user_account" show-overflow-tooltip />
                    <el-table-column label="线路名称" prop="title" show-overflow-tooltip />
                    <el-table-column label="出发地点" prop="start_address" show-overflow-tooltip />
                    <el-table-column label="到达地点" prop="end_address" show-overflow-tooltip />
                    <el-table-column label="简介" prop="desc" show-overflow-tooltip />
                    <el-table-column label="是否热门" prop="is_hot">
                        <template #default="{ row }">
                            <el-tag class="ml-2" :type="row.is_hot ? 'primary' : 'danger'"
                                >{{ row.is_hot_value }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="排序" prop="sort" show-overflow-tooltip />
                    <el-table-column label="状态" prop="status">
                        <template #default="{ row }">
                            <el-tag class="ml-[-10px]" :type="row.status_remark"
                                >{{ row.status_value }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="260" fixed="right">
                        <template #default="{ row }">
                            <el-button
                                v-perms="['travel.line/update_status']"
                                type="primary"
                                link
                                @click="handleApprove(row)"
                            >
                                审批
                            </el-button>
                            <el-button v-perms="['travel.line_price/lists']" type="primary" link>
                                <router-link
                                    :to="{
                                        path: getRoutePath('travel.line_price/lists'),
                                        query: {
                                            id: row.id
                                        }
                                    }"
                                >
                                    <div></div>
                                    <div v-if="row.pending_status == 1" style="color: red">
                                        价格审核
                                    </div>
                                    <div v-else>价格查看</div>
                                </router-link>
                            </el-button>
                            <el-button
                                v-perms="['travel.line/edit']"
                                type="primary"
                                link
                                @click="handleEdit(row)"
                            >
                                编辑
                            </el-button>
                            <el-button
                                v-perms="['travel.line/delete']"
                                type="danger"
                                link
                                @click="handleDelete(row.id)"
                            >
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <div class="flex mt-4 justify-end">
                <pagination v-model="pager" @change="getLists" />
            </div>
        </el-card>
        <edit-popup
            v-if="showEdit"
            ref="editRef"
            :dict-data="dictData"
            @success="getLists"
            @close="showEdit = false"
        />
    </div>
    <approve-popup
        v-if="showApprove"
        ref="approveRef"
        :id="approveId"
        @success="getLists"
        @close="showApprove = false"
    />
    <import-popup
        v-if="showImport"
        ref="importRef"
        @success="getLists"
        @close="showImport = false"
    />
</template>

<script lang="ts" setup name="lineLists">
import { usePaging } from '@/hooks/usePaging'
import { useDictData, useDictOptions } from '@/hooks/useDictOptions'
import { apiLineLists, apiLineDelete } from '@/api/line'
import { getRoutePath } from '@/router'
import feedback from '@/utils/feedback'
import EditPopup from './edit.vue'
import { travelAgencyAll } from '@/api/travel_agency.ts'
import ApprovePopup from '@/views/travel_agency/line/components/ApprovePopup.vue'

import ImportPopup from '@/views/travel_agency/line/components/ImportPopup.vue'
import axios from 'axios'
import { fileDownload } from '@/api/file.ts'

const editRef = shallowRef<InstanceType<typeof EditPopup>>()
const approveRef = shallowRef<InstanceType<typeof ApprovePopup>>()
const importRef = shallowRef<InstanceType<typeof ImportPopup>>()
const showImport = ref(false)
// 是否显示编辑框
const showEdit = ref(false)
// 是否显示审批框
const showApprove = ref(false)
// 审批的线路ID
const approveId = ref<number>(0)
// 查询条件
const queryParams = reactive({
    travel_agency_id: '',
    title: '',
    start_address: '',
    end_address: '',
    desc: '',
    is_hot: '',
    sort: '',
    status: ''
})

// 选中数据
const selectData = ref<any[]>([])

// 表格选择后回调事件
const handleSelectionChange = (val: any[]) => {
    selectData.value = val.map(({ id }) => id)
}

// 获取字典数据
const { dictData } = useDictData('approval_status,is_hot')

// 分页相关
const { pager, getLists, resetParams, resetPage } = usePaging({
    fetchFun: apiLineLists,
    params: queryParams
})

// 添加
const handleAdd = async () => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('add')
}

// 编辑
const handleEdit = async (data: any) => {
    showEdit.value = true
    await nextTick()
    editRef.value?.open('edit')
    editRef.value?.setFormData(data)
}

// 删除
const handleDelete = async (id: number | any[]) => {
    await feedback.confirm('确定要删除？')
    await apiLineDelete({ id })
    getLists()
}
// 审批
const handleApprove = async (row: any) => {
    showApprove.value = true
    await nextTick()
    approveRef.value?.open(row.id)
}
const { optionsData } = useDictOptions<{
    trave_agency: any[]
}>({
    trave_agency: {
        api: travelAgencyAll
    }
})

const handleImport = async (id: number) => {
    if (!id) {
        feedback.msgError('请选择旅行社后才能导入')
        return
    }
    showImport.value = true
    await nextTick()
    importRef.value?.open(id)
}

const downloadTemplate = async () => {
    try {
        const fileName = 'line.xls' // 替换为你的模板名称

        const response = await fileDownload({
            file: fileName
        })
        const blob = new Blob([response], { type: 'application/vnd.ms-excel' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = fileName
        link.click()
        window.URL.revokeObjectURL(url)
        ElMessage.success('模板下载成功')
    } catch (error: any) {
        console.error('文件下载失败:', error)
        if (error.response?.status === 404) {
            ElMessage.error('文件不存在或已被删除')
        } else {
            ElMessage.error('网络异常，请重试')
        }
    }
}
getLists()
</script>
